<template>
  <div class="app-container">

    <el-image-viewer
      v-if="showImageViewer"
      :on-close="() => { showImageViewer = false }"
      :initial-index="viewIndex"
      :url-list="images">
    </el-image-viewer>

    <Modal v-model="upload.open"
           title="商品批量导入"
           :mask-closable="false"
    >
      <div class="batch-create-container">
          <div
            class="params-form-wrapper"
            style="color: #606266;">
            <el-row style="margin-bottom: 15px">
              <div style="border: 1px solid #e6ebf5; padding: 15px 20px">
                <el-button style="float: right; padding: 3px 0" type="text" @click="$http.download('/static/template', '新品入场导入模板.xlsx')">
                  <i class="el-icon-document">导入模板</i>
                </el-button>
                <span style="color: #909399; font-size: 12px;">
                  下载Excel导入模板，并填写内容
                </span>
              </div>
            </el-row>
            <el-row>
              <el-upload
                ref="uploadImport"
                :multiple="false"
                :limit="1"
                :on-error="onFileUploadError"
                :on-success="onFileUploadSuccess"
                :http-request="fileUpload"
                :with-credentials="true"
                :auto-upload="false"
                class="upload-file"
                drag
                style="display:block"
                action="/business/sku/importData"
                accept=".xls,.xlsx,.csv">
                <i class="el-icon-upload"/>
                <div class="el-upload__text" style="color: #909399">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" class="el-upload__tip" style="color: #909399">仅支持单文件上传，支持xlsx/xls/csv文件格式，且不超过10MB</div>
              </el-upload>
            </el-row>
          </div>
        </div>
      <div slot="footer">
        <div class="button-container" style="text-align: center;">
          <el-button :loading="upload.loading" type="primary" style="width: 50%" @click="() => submitUpload('uploadImport')">
            确　定
          </el-button>
        </div>
      </div>
    </Modal>

    <Modal v-model="editModalOpen"
           title="编辑图片"
           width="600"
           :closable="false"
    >
      <el-row>
        <el-upload
            size="small"
            ref="uploadImage"
            :auto-upload="false"
            :limit="5"
            :on-change="onImageChange"
            :with-credentials="true"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".jpg,.png,.jpeg"
            action="/upload/picture"
            list-type="picture-card">
            <i slot="default" class="el-icon-plus"/>
            <div :class="file.master?'master':'slaver'" slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                <i class="el-icon-download"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
              <span v-if="!file.master" class="set-master" @click="handleSetMaster">
                设为主图
              </span>
            </div>
          </el-upload>
      </el-row>
      <div slot="footer">
        <Button @click="handleCancelEdit">取消</Button>
        <Button @click="() => confirmEdit()" type="primary">确定</Button>
      </div>
    </Modal>

    <Modal
      title="导入失败"
      v-model="showErrorImport"
      @on-ok="showErrorImport = false">
      <List header="商品列表" border size="small">
        <ListItem v-for="(item,index) in errorLines" :key="index">{{item}}</ListItem>
      </List>
    </Modal>

    <div class="app-content-container">
      <grid-table ref="gridTable"
                  name="SkuManager"
                  ref-form="searchForm"
                  :data="skuTableData"
                  :table-id="2"
                  :perfect="false"
                  :loading.sync="loading"
                  :query="query"
                  :slot-column="skuSlotColumn"
                  :buttons="buttons"
                  @remote-method="getList">
        <template v-slot:form>
          <el-form :inline="true" ref="searchForm" v-model="query" size="mini">
            <el-form-item label="商品搜索" prop="searchKey">
              <el-input v-model="query.searchValue" style="width: 300px" clearable size="small" @keydown.enter.native="getList($event)">
                <el-select style="width:120px" v-model="query.searchKey" slot="prepend" placeholder="请选择条件" size="small">
                  <el-option v-for="item in searchTypes" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item label="商品状态" prop="status">
              <el-select v-model="query.status" placeholder="请选择" clearable size="small">
                <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="建档日期" prop="createDate">
              <date-picker :value.sync="query.beginTimes" size="small"/>
            </el-form-item>
          </el-form>
        </template>
      </grid-table>
    </div>

  </div>
</template>

<script>
  import DatePicker from '@/components/DatePicker'
  import GridTable from '@/components/GridTable/index'
  import { listSku, sync } from '@/api/business/sku'
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  import { getToken } from "@/utils/auth"
  import download from "@/utils/download"
  import {upload} from "@/api/upload";
  import request from '@/utils/request';

  export default {
    name: 'Sku',
    components: { ElImageViewer, DatePicker, GridTable },
    data() {
      const validateIsMulPacket = (rule, value, callback) => {
        if (value === '1' && this.temp.packetTableData.length === 0) {
          callback(new Error('已勾选多包装单位，必须填写多包装'))
        } else {
          callback()
        }
      }
      return {
        errorLines: [],
        currentRow: undefined,
        tempRow: undefined,
        showErrorImport: false,
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "商品资料导入",
          // 是否禁用上传
          loading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: "/business/sku/importData",
        },
        images: [],
        activeTab: 'contractTab',
        baseRules: {
          ismulpacket: [
            { validator: validateIsMulPacket, trigger: 'change' }
          ]
        },
        showImageViewer: false,
        skuSlotColumn: {
          category: {
            default: ({ row }) => {
              return [<div>{ row.categoryCode }<br/>{ row.clsname }</div> ]
            }
          },
          pluname: {
            default: ({ row }) => {
              return [<div>{ row.skuName } { row.spec }/{ row.unit }<br/>{ row.skuCode }</div>]
            }
          },
          status: {
            default: ({ row }) => {
              const type = row.status == 1 ? 'success' : row.status == 2 ? 'warning' : 'danger'
              return [<el-tag type={type} class="tag-item" size="mini" effect="dark" >{ this.selectDictLabel(this.statusOptions, row.status) }</el-tag>]
            }
          },
          operator: {
            default: ({ row }) => {
              return [
                <vxe-button type='text' nativeOnClick={ () => { this.onEdit(row) } }>编辑</vxe-button>,
                <vxe-button type='text' nativeOnClick={ () => { this.onPreview(row) } }>预览</vxe-button>
              ]
            }
          },
          picture: {
            default: ({ row }) => {
              let src = download.BASE_IMAGE_API+'/'+row.mainPic
              return [
                <el-image src={src} fit="contain" lazy>
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              ]
            }
          }
        },
        editModalOpen: false,
        skuTableData: [],
        searchTypes: [
          { value: 'sku_code', name: '商品编码' },
          { value: 'barcode', name: '商品条码' },
          { value: 'sku_name', name: '商品名称' }
        ],
        query: {
          searchValue: undefined,
          searchKey: undefined,
          limit: 20,
          status: undefined,
          category: '',
          beginTimes: [],
          total: 0,
          pageNum: 1,
          pageSize: 20
        },
        filterToggle: false,
        loading: false,
        imageLimit: 5,
        fileList: [],
        viewIndex: 0,
        statusOptions: [],
        buttons: [
          { type: 'import', click: () => { this.upload.open = !this.upload.open } },
          { type: 'search', status: 'success' },
          { type: 'setting' },
          { type: 'sync', name: 'ERP同步', click: this.handleSync, icon: 'sync', permit: '*'}
        ],
        dirty: false,
        masterPic: undefined
      }
    },
    created() {
      this.getList();
      this.getDicts("business_sku_status").then(response => {
        this.statusOptions = response.data;
      });
      this.query.searchKey = this.searchTypes[0].value
    },
    methods: {
      handleSetMaster() {
        this.dirty = true
      },
      handleRemove(file) {
        let index = this.fileList.indexOf(file)
        this.fileList.splice(index, 1)
        this.images.splice(index, 1)
        // 设置主图
        if (this.fileList.length > 0) {
          this.masterPic = this.fileList[0]
          this.masterPic.master = true
        } else {
          this.masterPic = undefined
        }
        if (file.master) {
          if (this.tempRow.photoList.length > 0) {
            this.tempRow.mainPic = this.tempRow.photoList[0]
            this.tempRow.photoList.splice(0, 1)
          } else {
            this.tempRow.mainPic = ''
          }
        } else {
          this.tempRow.photoList.splice(index-1, 1)
        }
        console.log(this.tempRow.mainPic, this.masterPic)
        this.dirty = true
      },
      handleDownload(file) {
        download.downloadImage(download.BASE_IMAGE_API+'/'+file.path, file.name)
      },
      handleCancelEdit() {
        if (this.dirty) {
          this.$Modal.confirm({
            title: '取消编辑',
            content: '当前修改内容尚未保存，是否要退出编辑？',
            onOk: () => {
              this.editModalOpen = false
              this.dirty = false
              this.currentRow = undefined
              this.tempRow = undefined
            }
          })
        } else {
          this.editModalOpen = false
        }
      },
      handlePictureCardPreview(file) {
        this.viewIndex = this.fileList.indexOf(file)
        console.log(this.fileList)
        this.images = this._.map(this.fileList, (item) => {
          return item.url
        })
        this.showImageViewer = true
      },
      handleSync() {
        this.$confirm('是否要同步ERP商品资料？', '提示').then(_ => {
          sync(1).then(res => {
            this.$notify({
              type: 'success',
              message: '后台正在进行商品同步',
              duration: 2000
            })
          })
        })
      },
      onEdit(row) {
        this.currentRow = row
        this.currentRow.photoList = this.currentRow.photos ? row.photos.split(",") : []
        this.fileList = this._.union(row.mainPic ? [{ url: row.mainPic, master: true }] : [], this.currentRow.photoList)
        this.fileList = this._.map(this.fileList, (path, index) => {
          let ext = ''
          if (typeof path === 'object' && path.master) {
            ext = path.url.split('.').pop()
            return { name: `${row.barcode}-${index}.${ext}`, path: path.url, url: download.BASE_IMAGE_API+'/'+path.url, master: true }
          } else {
            ext = path.split('.').pop()
            return { name: `${row.barcode}-${index}.${ext}`, path: path, url: download.BASE_IMAGE_API+'/'+path, master: false }
          }
        })
        this.dirty = false
        this.editModalOpen = true
        this.tempRow = _.cloneDeep(row)
        this.masterPic = this.fileList.length > 0 ? this.fileList[0] : undefined
        console.log(this.fileList)
      },
      // 查看图片
      onPreview(row) {
        let list = []
        list = this._.union(row.mainPic ? [row.mainPic] : [], row.photos ? row.photos.split(",") : [])
        this.images = _.map(list, (item) => `${download.BASE_IMAGE_API}/${item}`)
        this.showImageViewer = true
      },
      fetchImportTemplate() {

      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      onFileUploadError(err, file, fileList) {
        showErrorImport = true
        this.upload.open = false
        console.log('error', err, file, fileList)
      },
      onFileUploadSuccess(response, file, fileList) {
        this.upload.open = false
        console.log('success', response, file, fileList)
      },
      handleExceed(files, fileList) {
        this.msgError(`当前限制最大可上传 ${this.imageLimit} 个文件`)
      },
      getList() {
        let data = this._.cloneDeep(this.query)
        if (data.category) {
          data.category = data.category[data.category.length - 1]
        }
        //data = this.addDateRange(data, data.createTime)
        if (data.status != undefined && data.status != null && data.status != '') {
          data.status = Number(data.status)
        }
        this.loading = true
        listSku(data).then(response => {
          this.skuTableData = response.rows
          this.query.total = response.total
          this.loading = false
        })
      },
      submitUpload(refName) {
        this.$refs[refName].submit()
      },
      fileUpload(payload) {
        const fd = new FormData()
        fd.append('file', payload.file)
        this.upload.loading = true
        request.post(payload.action, fd)
          .then(res => {
            this.upload.loading = false
            if (res.code !== 200) {
            } else {
              this.errorLines = []
              this.$notify({
                title: '商品批量创建',
                type: 'success',
                message: '导入成功',
                duration: 2000
              })
            }
          })
          .catch(res => {
            this.errorLines = res.msg.replace(/^;|;$/g, '').split(';')
            let msg = this.errorLines[0]
            this.errorLines[0] = msg.substring(msg.indexOf("错误如下：")+5, msg.length)
            this.showErrorImport = true
            this.upload.open = false
            this.upload.loading = false
          })
      },
      confirmEdit() {
        const fd = new FormData()
        this.fileList.forEach((item) => {
          if (item.status !== 'success' && this.masterPic != item) {
            fd.append('newFiles', item.raw)
          }
        })
        if (this.masterPic) {
          console.log(this.masterPic)
          fd.append('masterFile', this.masterPic.raw)
        }
        this._.forEach(this.tempRow, (value, key) => {
          fd.append(key, value)
        })
        fd.set('photos', this.tempRow.photoList.join(','))
        request.post('/upload/picture', fd)
          .then(res => {
            this.notifySuccess('保存成功')
            this.editModalOpen = false
            this.images = []
            this.masterPic = undefined
            this.getList()
          })
          .catch(res => {
            this.msgError(res.msg)
          })
      },
      onImageChange(file, fileList) {
        const isImage = (file.raw.type.indexOf('image') >= 0)
        if (!isImage) {
          this.msgError('上传文件类型只能是图片格式')
          fileList.splice(fileList.indexOf(file), 1)
        }
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) {
          this.msgError('上传图片大小不能超过10MB')
          fileList.splice(fileList.indexOf(file), 1)
        } else {
          this.fileList = fileList
          if (this.fileList.length === 1) {
            this.tempRow.mainPic = `/${this.fileList[0].uid}.${this.fileList[0].raw.type.split('/').pop()}`
            this.masterPic = this.fileList[0]
            this.masterPic.master = true
          } else {
            if (!this.tempRow.photoList) {
              this.tempRow.photoList = []
            }
            this.tempRow.photoList.push(`/${file.uid}.${file.raw.type.split('/').pop()}`)
          }
        }
        console.log(this.tempRow.mainPic, this.fileList)
        return isImage && isLt10M
      },
    }
  }
</script>

<style scoped>
</style>
